﻿//===========================================================================================================================
// Cuberry - http://www.cuberry.net
// Copyright (c) 2012
// by Peacequare® - Amir Moussa
//===========================================================================================================================
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License 
// as published by the Free Software Foundation, either version 3 of the License, or any later version.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// This program is distributed in the hope that it will be useful.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//===========================================================================================================================

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using P2.Cuberry.Framework.BOLBase;
using P2.Cuberry.Framework.Helper;
using P2.Cuberry.Framework.Helper.Configuration;
using P2.Cuberry.Framework.Security;
using P2.Cuberry.Modules.Framework.ModuleManager.DAL;


namespace P2.Cuberry.Modules.Framework.ModuleManager.BusinessEntities
{
    public class XConfigLogFields : BizObject, INotifyPropertyChanged
    {

        #region Constructors

        public XConfigLogFields()
        {
            Modified = false;
        }


        public XConfigLogFields(DAL.XConfigLogFields logFields)
        {
            Load(logFields);
            Modified = false;
        }

        #endregion

        #region Members

        int _trackingId = 0;
        public int TrackingId
        {
            get { return _trackingId; }
            set
            {
                if (value != _trackingId)
                {
                    _trackingId = value;
                    Modified = true;
                }
            }
        }

        string _fieldEntityName = String.Empty;
        public string FieldEntityName
        {
            get { return _fieldEntityName; }
            set
            {
                if (value != _fieldEntityName)
                {
                    _fieldEntityName = value;
                    Modified = true;
                }
            }
        }

        string _fieldName = String.Empty;
        public string FieldName
        {
            get { return _fieldName; }
            set
            {
                if (value != _fieldName)
                {
                    _fieldName = value;
                    Modified = true;
                }
            }
        }

        string _moduleName = String.Empty;
        public string ModuleName
        {
            get { return _moduleName; }
            set
            {
                if (value != _moduleName)
                {
                    _moduleName = value;
                    Modified = true;
                }
            }
        }

        public Module ParentModule { set; get; }

        #endregion

        #region Read Operations

        public void Load(DAL.XConfigLogFields sourceEntity)
        {
            try
            {
                if (sourceEntity != null)
                {
                    this.TrackingId = sourceEntity.TrackingID;
                    this.FieldEntityName = sourceEntity.EntityName;
                    this.FieldName = sourceEntity.FieldName;
                    this.ModuleName = sourceEntity.ModuleName;
                                       
                    //Default Fields                
                    this.CreatedBy = sourceEntity.CreatedBy;
                    this.CreatedOn = sourceEntity.CreatedOn;
                    this.EditedBy = sourceEntity.EditedBy;
                    this.EditedOn = sourceEntity.EditedOn;
                    this.Timestamp = sourceEntity.TStamp;
                    //this.StatusID = sourceEntity.StatusID.GetValueOrDefault(P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus.GetInitialStatus(this.EntityName).StatusID);
                }
                else
                {
                    this.TrackingId = 0;
                    this.FieldEntityName = String.Empty;
                    this.FieldName = String.Empty;
                    this.ModuleName = String.Empty;

                    //Default Fields
                    this.CreatedBy = String.Empty;
                    this.EditedBy = String.Empty;
                    P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus initStatus = P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus.GetInitialStatus(this.EntityName);
                    this.StatusID = initStatus.StatusID;
                }
                Modified = false;
            }
            catch (System.Exception ex)
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }

        protected P2TransactionMessage FillMyObject()
        {
            P2TransactionMessage tMsg = new P2TransactionMessage();
            try
            {
                string connectionString = ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResources);
                using (ModuleManagerDataContext db = new ModuleManagerDataContext(connectionString))
                {
                    var transactions = from tran in db.XConfigLogFields
                                       where tran.ModuleName == this._moduleName
                                       select tran;
                    if (transactions.Count() > 0)
                    {
                        foreach (var transaction in transactions)
                        {
                            Load(transaction);
                        }
                    }
                }

                tMsg.TransactionStatus = "green";
                tMsg.MessageText = "TMsg_FillMyObjectSuceeded";
            }
            catch (Exception ex) //AM:TC!!
            {
                tMsg.TransactionStatus = "red";
                tMsg.MessageText = "Error_Error";
                tMsg.MessageFreeText = ex.Message;
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }

            this.MessageStack.Add(tMsg);
            return tMsg;
        }

        public static ObservableCollection<XConfigLogFields> GetFieldTracking(Module xMod, PropertyChangedEventHandler onChange)
        {
            try
            {
                ObservableCollection<XConfigLogFields> itemsCollection = new ObservableCollection<XConfigLogFields>();

                string connectionString = ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResources);
                using (ModuleManagerDataContext db = new ModuleManagerDataContext(connectionString))
                {
                    var xfieldTrackings = from tranItem in db.XConfigLogFields
                                        where tranItem.ModuleName == xMod.ModuleName
                                        select tranItem;
                    if (xfieldTrackings.Count() > 0)
                    {
                        foreach (var fieldTracking in xfieldTrackings)
                        {
                            itemsCollection.Add(new XConfigLogFields(fieldTracking) { ParentModule = xMod });
                        }
                    }
                }

                return itemsCollection;
            }
            catch (System.Exception ex)
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", "XAppResources", System.Reflection.MethodInfo.GetCurrentMethod().Name));
                return null;
            }
        }

        #endregion

        #region Update Operations

        public P2MessageStack InsertAndUpdate(ModuleManagerDataContext db)
        {
            P2MessageStack MessageStack = new P2MessageStack();

            try
            {
                if (string.IsNullOrEmpty(this.CreatedBy)) 
                    this.CreatedBy = User.Current.UserID;
                
                this.EditedBy = User.Current.UserID;
                DAL.XConfigLogFields editedItem;
                
                if (this.TrackingId < 1)
                {
                    editedItem = new DAL.XConfigLogFields()
                    {
                        EntityName = this.FieldEntityName,
                        FieldName = this.FieldName,
                        ModuleName = this.ModuleName,

                        //Default Fields
                        CreatedBy = User.Current.UserID,
                        CreatedOn = DateTime.Now,
                        EditedBy = User.Current.UserID,
                        EditedOn = DateTime.Now,
                        //StatusID = this.StatusID
                    };
                    db.AddToXConfigLogFields(editedItem);
                }
                else
                {
                    editedItem = (from ti in db.XConfigLogFields
                                  where ti.TrackingID == this.TrackingId
                                  select ti).First();
                    if (editedItem.TStamp == this.Timestamp)
                    {
                        editedItem.EntityName = this.FieldEntityName;
                        editedItem.FieldName = this.FieldName;
                        editedItem.ModuleName = this.ModuleName;

                        //Default Fields
                        editedItem.EditedBy = User.Current.UserID;
                        editedItem.EditedOn = DateTime.Now;
                        //editedItem.StatusID = this.StatusID;

                        //track changes!
                        //this.SaveChangeLog(-No Tracking-);
                    }
                    else
                    {
                        MessageStack.Add(new P2TransactionMessage("red", P2Translator.GetResource("TMsg_PaymentNotUpdated")));
                    }
                }
            }
            catch (Exception ex)
            {
                MessageStack.Add(new P2TransactionMessage("red", P2Translator.GetResource("Error_Error")));
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
            return MessageStack;
        }

        public void Delete(ModuleManagerDataContext db)
        {
            if (this.TrackingId != 0)
            {
                var item = (from ti in db.XConfigLogFields
                            where this.TrackingId == ti.TrackingID
                            select ti).First();
                db.DeleteObject(item);
                db.SaveChanges();
            }
        }

        #endregion

        #region Validation
        //Empty
        #endregion

        #region "Copy operations"

        public XConfigLogFields GetCopy()
        {
            try
            {
                XConfigLogFields newItem = new XConfigLogFields();
                newItem.ParentModule = this.ParentModule;
                newItem.FieldEntityName = this.FieldEntityName;
                newItem.FieldName = this.FieldName;
                newItem.ModuleName = this.ModuleName;

                newItem.Timestamp = this.Timestamp;
                newItem.Modified = this.Modified;
                return newItem;
            }
            catch (System.Exception ex)
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
                return null;
            }
        }

        public void UpdateFrom(XConfigLogFields sourceItem)
        {
            try
            {
                this.ParentModule = sourceItem.ParentModule;
                this.FieldEntityName = sourceItem.FieldEntityName;
                this.FieldName = sourceItem.FieldName;
                this.ModuleName = sourceItem.ModuleName;

                this.Timestamp = sourceItem.Timestamp;
                this.Modified = sourceItem.Modified;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }

        #endregion

        #region Property Changed

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler Handler = PropertyChanged;
            if (Handler != null) 
                Handler(this, new PropertyChangedEventArgs(propertyName));
        }

        public void OnAllPropertiesChanged()
        {            
            OnPropertyChanged("TrackingId");
            OnPropertyChanged("FieldEntityName");
            OnPropertyChanged("FieldName");
            OnPropertyChanged("ModuleName");
        }

        #endregion

        #region Validator

        public override P2Validator Validator
        {
            get
            {
                if (_validator == null)
                {
                    _validator = new P2Validator(Properties.Settings.Default.ModuleName, this.EntityName, "TrackingId", this);
                }
                return _validator;
            }
        }

        #endregion
    }
}
